﻿using PasswordManagerMVC.Models;
using System;
using System.Web;

namespace PasswordManagerMVC.Utilities
{
    public class SessionManager
    {
        public static bool NotNull(HttpContextBase context,
            string key)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            return context.Session[key] != null;
        }

        public static void AddUser(HttpContextBase context,
            int uid, string name)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            context.Session["UserInfo"] = new LogOnModel
            {
                ID = uid,
                UserName = name,
            };
        }

        public static bool HasUser(HttpContextBase context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            return NotNull(context, "UserInfo");
        }

        public static bool TryGetUser(HttpContextBase context,
            out LogOnModel user)
        {
            user = null;
            if (context == null)
                throw new ArgumentNullException("context");

            var model = (LogOnModel)context.Session["UserInfo"];

            if (model == null)
                return false;

            user = model;
            return true;
        }

        public static object Add(HttpContextBase context,
            string key, object value)
        {
            context.Session[key] = value;

            return context.Session[key];
        }

        public static object Get(HttpContextBase context, 
            string key)
        {
            return context.Session[key];
        }
    }
}